package Array_and_String;

import java.util.*;

/*
反转字符串中的单词 III
给定一个字符串s，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
示例 1：
输入：s = "Let's take LeetCode contest"
输出："s'teL ekat edoCteeL tsetnoc"
示例 2:
输入： s = "Mr Ding"
输出："rM gniD"
作者：LeetCode
链接：https://leetcode.cn/leetbook/read/array-and-string/c8su7/
 */
public class _53反转字符串中的单词3 {
    public static void main(String[] args) {

        String str = "Let's take LeetCode contest";

        reverseWords(str);

    }

    public static String reverseWords(String s) {
        String[] strings = s.split("\s");
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < strings.length; i++) {
            StringBuilder temp = new StringBuilder(strings[i]);
            temp.reverse();
            if (i != strings.length - 1) {
                sb.append(temp);
                sb.append("\s");
            }else {
                sb.append(temp);
            }

        }

        return sb.toString();
    }

    //官解
        public String reverseWords2(String s) {
            StringBuffer ret = new StringBuffer();
            int length = s.length();
            int i = 0;
            while (i < length) {
                int start = i;
                while (i < length && s.charAt(i) != ' ') {
                    i++;
                }
                for (int p = start; p < i; p++) {
                    ret.append(s.charAt(start + i - 1 - p));
                }
                while (i < length && s.charAt(i) == ' ') {
                    i++;
                    ret.append(' ');
                }
            }
            return ret.toString();
        }

}
